﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Com.Ctrip.Framework.Apollo;
using Com.Ctrip.Framework.Apollo.Enums;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using StackExchange.Profiling.Internal;
using NetMicro.Core.Exceptions;
using NetMicro.Core.Helper;

namespace NetMicro.Core.ConfigureOptions
{
    /// <summary>
    /// config配置中心添加
    /// </summary>
    public static class HostConfigBuilderExtensions
    {


        /// <summary>
        /// 系统默认注入配置中心
        /// </summary>
        /// <param name="host"></param>
        /// <param name="programName"></param>
        /// <returns></returns>
        public static IHostBuilder UseConfigHostBuilder(this IHostBuilder host)
        {
            return host
                  .ConfigureAppConfiguration((context, config) =>
                  {
                      App.SetHostEnvironment(context.HostingEnvironment);
                      Console.WriteLine($"环境变量：{App.EnvironmentName}");
                      //读取本地配置
                      IConfigurationRoot localconfig = new ConfigurationBuilder()
                                       .SetBasePath(Directory.GetCurrentDirectory())
                                         .AddJsonFile("appsettings.json")
                                         .AddJsonFile($"appsettings.{App.EnvironmentName}.json")
                                         .Build();
                      bool local = localconfig.GetSection("Local").Get<bool>();

                      Console.WriteLine($"是否开启本地：{local}");
                      if (!local)
                      {
                          //从本地配置里读取apollo相关信息
                          IConfigurationSection configSection = localconfig.GetSection("apollo");
                          if (!configSection.Exists())
                          {
                              throw new ConfigException($"Can not find section:Apollo from appsettings.{App.EnvironmentName}.json");
                          }
                          ApolloOptions apolloOptions = configSection.Get<ApolloOptions>();

                          Console.WriteLine($"Apollo配置：{apolloOptions.ToJson()}");
                          apolloOptions.Env = App.EnvironmentName switch
                          {
                              "Development" => Env.Dev,
                              "Staging" => Env.Fat,
                              "Uat" => Env.Uat,
                              "Production" => Env.Pro,
                              _ => Env.Dev,
                          };
                          IConfigurationRoot apollo = config
                             .AddApollo(apolloOptions)
                             .AddDefault()
                             .AddNamespace("Common.BaseConfig").Build();
                          ConsoleApolloLog(apollo);
                      }
                      App.SetConfiguration(config.Build());
                  });
        }

        /// <summary>
        /// 配置文件控制台以及日志打印
        /// </summary>
        /// <returns></returns>
        public static void ConsoleApolloLog(IConfigurationRoot root)
        {
            //todo:baseconfig 应该添加到配置文件
            IEnumerable<string> currentConfig = ApolloConfigurationManager.Manager.GetConfig("application").Result.GetPropertyNames();
            IEnumerable<string> baseConfig = ApolloConfigurationManager.Manager.GetConfig("Common.BaseConfig").Result.GetPropertyNames();
            List<string> keys = new List<string>();
            keys.AddRange(currentConfig);
            keys.AddRange(baseConfig);
            if (!keys.Any())
            {
                throw new ConfigException($"未获取到配置中心配置项");
            }
            Console.WriteLine("Program.Main.Start");
            Console.WriteLine("Program.Main.Config");
            foreach (string item in keys)
            {
                Console.WriteLine($"{item}：{root[item]}");
            }
        }


    }
}
